package com.sjgtw.cloud.web.gridManage.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sjgtw.cloud.common.core.constant.CacheConstants;
import com.sjgtw.cloud.common.core.utils.DateUtils;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.redis.service.RedisService;
import com.sjgtw.cloud.service.SystemServerService;
import com.sjgtw.cloud.system.api.model.LoginUser;
import com.sjgtw.cloud.web.gridManage.domain.GridManage;
import com.sjgtw.cloud.web.gridManage.mapper.GridManageMapper;
import com.sjgtw.cloud.web.gridManage.service.IGridManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 防洪网格化管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-03-09
 */
@Service
public class GridManageServiceImpl implements IGridManageService
{
    @Autowired
    private GridManageMapper gridManageMapper;

    @Autowired
    private SystemServerService systemServerService;

    @Autowired
    private RedisService redisService;

    /**
     * 查询防洪网格化管理
     * 
     * @param id 防洪网格化管理主键
     * @return 防洪网格化管理
     */
    @Override
    public GridManage selectGridManageById(Long id)
    {
        return gridManageMapper.selectGridManageById(id);
    }

    /**
     * 查询防洪网格化管理列表
     * 
     * @param gridManage 防洪网格化管理
     * @return 防洪网格化管理
     */
    @Override
    public List<Map<String,Object>> selectGridManageList(GridManage gridManage)
    {
        return gridManageMapper.selectGridManageList(gridManage);
    }

    @Override
    public List<GridManage> selectGridManageList2(GridManage gridManage) {
        return gridManageMapper.selectGridManageList2(gridManage);
    }

    /**
     * 新增防洪网格化管理
     * 
     * @param gridManage 防洪网格化管理
     * @return 结果
     */
    @Override
    public int insertGridManage(GridManage gridManage)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        gridManage.setCreateBy(user.getUsername());
        gridManage.setCreateTime(new Date());
        return gridManageMapper.insertGridManage(gridManage);
    }

    /**
     * 修改防洪网格化管理
     * 
     * @param gridManage 防洪网格化管理
     * @return 结果
     */
    @Override
    public int updateGridManage(GridManage gridManage)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        gridManage.setUpdateBy(user.getUsername());
        gridManage.setUpdateTime(new Date());
        return gridManageMapper.updateGridManage(gridManage);
    }

    /**
     * 批量删除防洪网格化管理
     * 
     * @param ids 需要删除的防洪网格化管理主键
     * @return 结果
     */
    @Override
    public int deleteGridManageByIds(Long[] ids)
    {
        return gridManageMapper.deleteGridManageByIds(ids);
    }

    /**
     * 删除防洪网格化管理信息
     * 
     * @param id 防洪网格化管理主键
     * @return 结果
     */
    @Override
    public int deleteGridManageById(Long id)
    {
        return gridManageMapper.deleteGridManageById(id);
    }

    @Override
    public List<String> check(List<GridManage> entities) {
        List<String> errors = new ArrayList<>();
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        List<String> deptNames = extractAndDeduplicateNames(entities);
        AjaxResult result = systemServerService.getDeptByNames(StringUtils.join(deptNames, ","));
        Map<String, Long> deptMap = new HashMap<>();
        if (result != null) {
            Object object = result.get("data");
            if (object != null) {
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                if (!jsonArray.isEmpty()) {
                    for (int i=0; i<jsonArray.size();i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        deptMap.put(json.getString("deptName"), json.getLong("deptId"));
                    }
                }
            }
        }

        for (GridManage entity : entities) {
            if (StringUtils.isEmpty(entity.getOneGrid())) {
                errors.add("序号为" + entity.getNum() + "行数据一级网格单位不能为空");
            } else if (deptMap.containsKey(entity.getOneGrid())) {
                entity.setOneGridId(deptMap.get(entity.getOneGrid()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据一级网格单位不存在");
            }

            if (StringUtils.isEmpty(entity.getTwoGrid())) {
                errors.add("序号为" + entity.getNum() + "行数据二级网格单位不能为空");
            } else if (deptMap.containsKey(entity.getTwoGrid())) {
                entity.setTwoGridId(deptMap.get(entity.getTwoGrid()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据二级网格单位不存在");
            }
            if (user != null) {
                entity.setCreateBy(user.getUsername());
            }
            entity.setCreateTime(DateUtils.getNowDate());
        }
        return errors;
    }

    @Override
    public void batchSave(List<GridManage> entities) {
        if (entities != null && entities.size() > 0) {
            if (entities.size() >= 200) {
                int index = 0;
                while (index <= entities.size()) {
                    int last = Math.min(index + 200, entities.size());
                    List<GridManage> temp = entities.subList(index, last );
                    if (temp != null && temp.size() > 0) {
                        gridManageMapper.batchSave(temp);
                    }
                    index += 200;
                }
            } else {
                gridManageMapper.batchSave(entities);
            }
        }
    }

    private static List<String> extractAndDeduplicateNames(List<GridManage> entities) {
        Set<String> uniqueNamesSet = new HashSet<>();

        for (GridManage entity : entities) {
            uniqueNamesSet.add(entity.getOneGrid());
            uniqueNamesSet.add(entity.getTwoGrid());
        }

        return new ArrayList<>(uniqueNamesSet);
    }
}
